<template>
	<div class="inquiry">
			<div class="inquiry-inner" :style="{'height':relHeight}"
			:class="[inputInquiry?'reduce-padding-bottom':'']" ref="dialogueWrap">
				<div v-for="(item,indexWrap) in dataList">
					<!--机器人-->
					<div class="robot-dialogue-wrap clearfix" v-for="(itemSon,indexSon) in item.stems"
					:id="'dialog'+item.sn" ref="box" :class="[item.end_finish?'disabled':'']" :sn="item.sn">
						<div v-if="itemSon.type=='Diagnosis' || (itemSon.type=='ButtonAskOtherSymptom' && !showButtonAskOtherSym)
							|| (itemSon.type=='ButtonAskPregnancy' && !showButtonAskPregnancy) || itemSon.type=='Notification'"></div>
						<div v-else>
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content">
								<p class="padd_30">{{itemSon.stem}}</p>
								<p class="robot-choose-item clearfix"
								v-if="itemSon.action.length>0" :class="[itemSon.finish?'disabled':'']"
									v-for="(itemSonSon,idx) in itemSon.action"
									@click="clickCommand(itemSonSon.commandId,itemSonSon.text)">
									<span class="left">{{itemSonSon.text}}</span>
									<span class="right iconfont">&#xe62b;</span>
								</p>
								<!--输入属性-->
								<p class="inputAttr" v-show="itemSon.type=='ButtonAskSymptomAttr'&& !itemSon.finish"
									@click="clickCommand('inputAttr')">
									<img src="../assets/img/input-attr.svg" alt="img" style="width:.48rem;height:.48rem;margin-top:-.1rem;"/>
									{{itemSon.buttonText}}
								</p>
							</div>
						</div>
						<!--是否怀孕--><!--以及需要判断才能展示的特殊样式-->
						<div class="robot-dialogue-wrap clearfix" v-if="itemSon.type=='ButtonAskPregnancy' && !itemSon.finish">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content-spe">
								<p class="padd_30">您是否处于怀孕状态？</p>
								<p class="inputAttr" @click="surePregnancyStatus">
									<img src="../assets/img/symptoms-sure-icon.svg" alt="img" class="small-icon"/>
									确定
								</p>
								<div class="clearfix other-symptoms-card">
									<div v-for="(item,index) in dataOptions" @click="choosePregnancy(index,item.key,item.text)">
										<p class="other-symptoms-text" :class="[pregnancyFlag==index?'pregnancyActive':'']">
											{{item.text}}
										</p>
									</div>
								</div>
							</div>
						</div>
						<!--怀孕提示-->
						<div class="robot-dialogue-wrap clearfix" v-if="itemSon.type=='Diagnosis' && !itemSon.disease">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content robot-content-pregnancy">
								<p class="padd_30">•   {{itemSon.stem}}</p>
							</div>
						</div>
						<!--危机提示-->
						<div class="robot-dialogue-wrap clearfix" v-if="itemSon.type=='Notification'">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content robot-content-notification">
								<p class="padd_30">•   {{itemSon.stem}}</p>
							</div>
						</div>
						<!--症状选择-->
						<div class="input-inquiry-wrap" v-if="itemSon.type=='ButtonAskSymptom' && inputInquiry">
							<p class="input-inquiry"  @click="clickToSymptom">
								<img src="../assets/img/input-inquiry.svg" alt="img" style="width:.4rem;height:.5rem;margin-top:-.2rem;"/>
								{{itemSon.buttonText}}
							</p>
							<div class="input-inquiry-val">
								<input type="text" placeholder="请输入您的症状，譬如头晕、恶心、发热..." @focus="showSendFreeImg" v-model="freeText"/>
								<img src="../assets/img/input-inquiry-val1.svg" alt="img" class="input-inquiry-val-img1"/>
								<img src="../assets/img/input-inquiry-val.svg" alt="img" class="input-inquiry-val-img" @click="sendFreeText" v-show="sendFreeImg"/>
							</div>
						</div>
						<!--第一次判断出来的诊断结果-->
						<div class="robot-dialogue-wrap clearfix"
							v-if="itemSon.disease && item.asking.type!='SaveOptions'">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content">
								<p class="padd_30">根据您描述的症状，AI系统初步预测与这些症状最相关的疾病为：</p>
								<p class="padd_30" v-for="(itemDis,idxDis) in itemSon.disease"
									style="font-weight:600;">{{idxDis+1}}.{{itemDis.text}}</p>
								<p class="robot-choose-item clearfix"
									@click="toresultPage(0)"
									:class="[disabledFlag?'disabled':'']">
									<span class="left">查看详情</span>
									<span class="right iconfont">&#xe62b;</span>
								</p>
							</div>
						</div>
						<!--诊断结果-->
						<div class="robot-dialogue-wrap clearfix robot-dialogue-wrap-result"
							v-if="itemSon.type=='Diagnosis' && itemSon.disease && item.asking.type=='SaveOptions'">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content-spe2">
								<div class="clearfix">
									<p class="left diagnostic-title">智能诊断结果</p>
									<p class="save-record-btn right" @click="saveRecordFn(item.asking.askName)" v-if="item.asking.type=='SaveOptions'">
										<img src="../assets/img/save-record.svg" alt="img" />
										<span>保存记录</span>
									</p>
								</div>

								<p class="text-left diagnostic-time">
									<img src="../assets/img/time-icon.svg" alt="img" style="width:.24rem;height:.24rem;margin-top:-.1rem;"/>
									{{currentDay}}
								</p>
								<div class="diagnostic-result-con">
									<p class="clearfix" @click="toresultPage(0)">
										<span class="left">您可能患有以下疾病：</span>
										<span class="right iconfont" style="color:#fff;">&#xe62b;</span>
									</p>
									<div class="diagnostic-list" v-for="(itemDis,idxDis) in itemSon.disease">
										<span class="diagnostic-probability">{{(itemDis.weight*100).toFixed(1)}}%</span>
										<span>{{itemDis.text}}</span>
									</div>
								</div>

							</div>
						</div>
						<!--是否还有其他症状 机器人卡片式-->
						<div class="robot-dialogue-wrap clearfix" v-if="itemSon.type=='ButtonAskOtherSymptom' &&!itemSon.finish">
							<p class="left">
								<img src="../assets/img/logo.png" alt="robot" class="robot-img"/>
							</p>
							<div class="left robot-content-spe">
								<p class="padd_30">
									<span>{{otherSymptomsTextGlobal}}</span>
									(可多选)
								</p>
								<p class="inputAttr" @click="sureOtherSymptoms">
									<img src="../assets/img/symptoms-sure-icon.svg" alt="img" class="small-icon"/>
									确定
								</p>
								<div class="clearfix other-symptoms-card">
									<div @click="chooseOtherSymptomsItem(index)" v-for="(itemOther,index) in otherSymptomsListGlobal" >
										<p class="other-symptoms-text" :class="[itemOther.show?'cardActive':'']">
											{{itemOther.text}}
											<span class="question-mark" v-if="itemOther.showQ==true">?</span>
										</p>
									</div>
								</div>
								<p class="none-symptom-wrap">
									<span class="other-none-symptom" @click="otherNoneSymFn()"
										:class="[otherSymptomsArr.length<=0?'cardActive':'other-none-symptom']">
										都没有
									</span>
								</p>
							</div>
						</div>
					</div>
					<!--患者-->
					<div class="patient-wrap clearfix" v-if="item.answer && itemAnswer.type" v-for="(itemAnswer,indexTest) in item.answer"
						:id="'dialog'+(item.sn+1)" ref="box" :class="[item.end_finish?'disabled':'']"
						@click.stop="showPopButtonFn(indexWrap)" :sn="item.sn+1">
						<p class="right patient-content" v-if="typeof(itemAnswer.value)=='string'">{{itemAnswer.value}}</p>
						<p class="right patient-content" v-else>
							<span v-for="(itemVal,index) in itemAnswer.value" class="style-border-right">
								{{itemVal}}
								<span v-if="index!=itemAnswer.value.length-1"> | </span>
							</span>
						</p>
						<div class="pop-button-warp" v-if="buttonActive==indexWrap && item.answer[1] && buttonActiveFlag" id="toggler-btn">
							<div class="arrow-up"></div>
							<p class="pop-button">
								<span @click.stop="clickCommand(itemText.command.id,'',itemAnswer.step,item.id,true,item.sn+1)"
								v-for="(itemText,indexText) in item.answer[1]" >{{itemText.text}} | </span>
								<span @click.stop="clickCommand('end-doctor-inquiry')">结束</span>
							</p>
						</div>
					</div>
					<!--新的开始-->
					<p class="user-protocol-btn" v-if="newStart && dataList[dataList.length-1].asking.type=='SaveOptions'"
					@click="clickCommand('end-doctor-inquiry')">
						<img src="../assets/img/new-beginning.svg" alt="img" class="small-icon"/>
						新的开始
					</p>
					<!--我同意按钮-->
					<p class="user-protocol-btn" v-if="showUserProtocol" @click.stop="clickCommand('agree')">
						<img src="../assets/img/i-agree.svg" alt="img" class="small-icon" />
						我同意
					</p>
					<!--继续、结束问诊-->
					<div class="inquiry-finish-wrap"
						v-if="dataList[dataList.length-1].stems[0].type=='Notification'">
						<div class="left" v-for="(itemWarn,WarnIdx) in item.asking.options">
							<div v-if="itemWarn.text=='结束问诊'" style="width:100%;">
								<img src="../assets/img/end-inquiry-img.svg" alt="robot" class="inquiry-finish-img">
								<p style="margin-top:-.1rem;color:#888;" @click="clickCommand('Notification',itemWarn.text,itemWarn.key)">{{itemWarn.text}}</p>
							</div>
							<span class="continue-btn"  @click="clickCommand('Notification',itemWarn.text,itemWarn.key)"  v-if="itemWarn.text=='继续问诊'">
								{{itemWarn.text}}
								<img src="../assets/img/continue-inquiry-img.svg" alt="img" class="inquiry-finish-img"/>
							</span>
						</div>
					</div>
				</div>
				<!--选择人员问诊-->
				<div style="background:#F8F8F8;" v-show="choosePersonnel">
					<scroller lock-y :scrollbar-x=false>
				      <div class="choose-personnel-list">
				        <div class="personnel-item left" @click="choosePersonneFn('female',35,'skip')">
				        		<p class="personnel-title-first">
				        			<img src="../assets/img/personnel-title-first.svg" alt="img" style="width:.3rem;height:.2rem;"/>
				        		</p>
				        		<p class="personnel-text" style="text-align:center;">新建</p>
				        </div>
				        <div v-if="!dataOptions && dataOptions.length<=0">
				        		 <div class="personnel-item left" @click="choosePersonneFn('male',35,'skip')">
								<p class="personnel-title">范例A</p>
								<p class="personnel-text">
									<span>男 |</span>
									<span>35岁</span>
								</p>
							</div>
							<div class="personnel-item left"	@click="choosePersonneFn('female',35,'skip')">
								<p class="personnel-title">范例B</p>
								<p class="personnel-text">
									<span>女 |</span>
									<span>35岁</span>
								</p>
							</div>
				        </div>
				        <div class="personnel-item left" v-for="(item,index) in dataOptions"
				        	@click="choosePersonneFn(item.gender,item.age,item.key,item.name)" v-else>
							<p class="personnel-title">{{item.name}}</p>
							<p class="personnel-text">
								<span v-if="item.gender=='male'">男 |</span>
								<span v-else-if="item.gender=='female'">女 |</span>
								<span>{{item.age}}岁</span>
							</p>
						</div>
				      </div>
				   </scroller>
				</div>
			</div>

		<!--遮罩层-->
		<div id="mask" v-show="showMask"></div>
		<!--基本信息和生命特征开始-->
		<div v-show="showEssentialInfo">
			<div class="show-choose-info">
				<!--part all-->
				<div class="info-content">
					<!--part1 基本信息-->
					<p class="text-center">
						<span class="info-title">基本信息</span>
						<span class="info-title">(必填)</span>
					</p>
					<div class="info-sexy clearfix">
						<p :class="[currentSexy=='male'?'sexy-active':'']" style="margin-right:0.5rem;" class="info-sex left" @click="changeSexyMenFn">男</p>
						<p :class="[currentSexy=='female'?'sexy-active':'']"  class="info-sex left" @click="changeSexyWomenFn">女</p>
					</div>
					<p class="sub-title">
						<span style="margin-top:-.1rem;">年龄</span>
						<span style="font-size:.6rem;color:#0FA3DA;font-weight:600;">{{value8}}</span>
					</p>
					<!--滑动组件-->

					<div class="clearfix" style="width:10rem;margin-left:1.6rem;">
						<p @click="reduceFn" class="left add-reduce">-</p>
				         <Slider v-model="value8" show-input class="left" :max="150" :step="5"></Slider>
				         <p @click="addFn" class="left reduce-add">+</p>
					</div>

				</div>
				<!--two 生命体征-->
				<div style="margin-top:1rem;">
					<p style="margin-bottom:.6rem;">
						<span class="sub-title">生命体征</span>
						<span class="sub-title">(选填)</span>
					</p>
					<div v-for="(item,index) in vitalSignList">
						<p class="vital-sign" @click="showSignActive(index)" v-show="!item.checked">{{item.text}}</p>
						<div class="clearfix vital-sign-active zoomIn" v-show="item.checked">
							<p class="clearfix left vital-sign-con animated fadeIn">
								<span class="left">{{item.text}}({{item.company}})</span>
								<input type="number" class="right sign-input" autofocus="autofocus"
								 @input="limitInput(index,item.inputValue)"
								 @blur="judgRange(index)"
								 v-model.number="item.inputValue"/>
							</p>
							<p class="left" @click="hideSignActive(index)" style="margin-left:.28rem;">
								<img src="../assets/img/revoke.svg" alt="robot" class="back-img">
							</p>
						</div>
						<p class="tiptext" v-show="item.showTip">*请输入0-{{item.max}}之间的数值</p>
					</div>
				</div>
			</div>
			<p class="choose-info-foot" @click="suresHideEssentialInfo">
				确定
			</p>
		</div>
		<!--生命体征结束 症状追问开始-->
		<div v-show="showSymptomsAsk">
			<!--症状追问content-->
			<div class="show-choose-info">
				<div class="info-content">
					<p class="symptom-inquiries-img">
						<img src="../assets/img/inquiries_bg.png" alt="robot">
						<span class="sym-text-inquiries">属性追问</span>
					</p>
					<!--part1-->
					<div v-for="(item,index) in pageListGlobal">
						<p class="text-center" style="color:#666;">{{index+1}}/{{pageListGlobal.length}}.{{item.text}}</p>
						<div class="swiper">
							<swiper :options="swiperOption">
						        <swiper-slide v-for="(itemSon,i) in item.optionsVal">
						        		<p class="left"
						        			v-for="(itemSonSon,iSon) in itemSon"
										@click="activeFun(index,itemSonSon)"
										:class="{'activeSwiper': itemSonSon.isActive, 'swiper-item-spe':item.strFlag, 'swiper-item':!item.strFlag}">
										{{itemSonSon.text}}
									</p>
						        </swiper-slide>
						        <div class="swiper-pagination" slot="pagination"></div>
						    </swiper>
						</div>
					</div>
				</div>
			</div>
			<p class="choose-info-foot" @click="determineInquiriesSym">
				确定
			</p>
		</div>
		<!--症状追问结束-->
		<div v-transfer-dom>
	      <confirm v-model="showConfirm"
	      show-input
	      title="创建病历"
	      placeholder='昵称不超过16个字符'
	      @on-confirm="onConfirm">
	      	<p style="text-align:center;">allalal</p>
	      </confirm>
	   </div>
	   <!--提示保存成功-->
	   <toast v-model="showSuccessToast" text="已保存至问诊记录" type="text" position="top"></toast>
	</div>

</template>

<script>
	import {Slider} from 'iView'
	import { Scroller,Popover,Confirm, XButton, TransferDomDirective as TransferDom,Toast} from 'vux'
	import 'swiper/dist/css/swiper.css'
	import { swiper, swiperSlide } from 'vue-awesome-swiper'
	//引入api
	import {urlStart,urlTalk} from '../api/api'
	import { handleDialogueSucCb,fetchType,getTime } from '../assets/js/common.js';
	import {mapState} from 'vuex'
	export default {
    		name: 'inquiry',
    		computed: {
            ...mapState(['selectedSymptom','inquiryDataList','diagnosisGlobal','scrollViewNumGlobal','continueFlag','otherSymptomsListGlobal',
            'pageListGlobal','answerGlobal','answerKeyGlobal','fromResultPageFlag','fromRecordsPageFlag','otherSymptomsTextGlobal','snGlobal',
            'fromUserPageFlag','finishInqFlagGlobal','scrollTopGlobal'])
        },
	    data(){
	    		return {
	    			showConfirm:false,//判断保存问诊名称的框
	    			showSuccessToast:false,//保存问诊成功显示
	    			value8: 35,
	    			relHeight:'',
	    			freeText:'',
	    			age:'',
	    			gender:'',
	    			currentSexy:'female',
	    			choosePersonKey:'',
	    			choosePersonName:'',
	    			//控制显示基本信息
	    			showMask:false,
	    			showEssentialInfo:false,
	    			showSymptomsAsk:false,
	    			inputInquiry:false,//控制显示症状选择的按钮
	    			choosePersonnel:false,//控制显示选择人员列表
	    			showPregnant:false,//控制是否怀孕
	    			showPregnantTip:false,
	    			newStart:false,//控制显示新的开始
	    			showUserProtocol:false,//用户协议
	    			sendFreeImg:false,//发送图标
	    			showPopButton:false,//控制显示长按pop
        			pageList: [],
        			activeArr:[],//追问症状存放选中的list
        			activeArrText:[],//追问症状选中的text
        			showButtonAskOtherSym:false,//控制显示是否还有其他症状文案
        			showButtonAskPregnancy:false,//控制显示是否怀孕文案
        			disabledFlag:false,
	            vitalSignList:[
	            		{text:'身高',company:'CM',checked:false,max:250,length:3,inputValue:'',showTip:false},
	            		{text:'体重',company:'KG',checked:false,max:250,length:3,inputValue:'',showTip:false},
	            		{text:'体温',company:'℃',checked:false,max:47,length:4,inputValue:'',showTip:false},
	            		{text:'高压',company:'mmHg',checked:false,max:240,length:3,inputValue:'',showTip:false},
	            		{text:'低压',company:'mmHg',checked:false,max:180,length:3,inputValue:'',showTip:false},
	            		{text:'心率',company:'次/分',checked:false,max:250,length:3,inputValue:'',showTip:false},
	            		{text:'呼吸频率',company:'次/分',checked:false,max:50,length:2,inputValue:'',showTip:false}
	            ],
	            pregnancyFlag:-1,
	            buttonActive:-1,
	            buttonActiveFlag:false,
	            otherSymptomsArr:[],//存放其他症状的数组
	            otherSymptomsText:[],//存放其他症状的text
	            spotLength:1,
	            activeIndex:false,
	            swiperOption: {　　
			        pagination: {
			          el: '.swiper-pagination'//分页器
			        }
			    },
			    dataList:[],
			    setAsh:false,//把点击过的置灰
			    resTalk:{},
			    resContents:[],
			    resSn:0,
			    dataOptions:[],
			    optionType:'',
			    scrollView:'',
			    stepNum:0,
			    stepList:[],
			    currentDay:'',
			    pregnancyKey:'',//存储传输怀孕的key
			    pregnancyText:'',//存储z展示怀孕的文案
      		}
	    },
	    	directives: {
		    TransferDom
		 },
	     components: {
	     	Slider,
		    Scroller,
		    Popover,
		    swiper,
		    swiperSlide,
		    Confirm,
		    XButton,
		    Toast
		 },
	    created(){
	    		//获取当前时间
	    		this.currentDay=getTime();
	    		//获取页面高度
	    		this.$nextTick(() => {
				//this.relHeight=`${document.documentElement.scrollHeight}px`; 这个方法不可行
				this.relHeight=document.documentElement.clientHeight+'px'

          	})
			this.enterPage();
	    		 //修改等功能点击其他位置消失
			document.addEventListener('click', (e) => {
				 var _con = $('.patient-conten');   // 设置目标区域
				  if(!_con.is(e.target) && _con.has(e.target).length === 0){
				    		this.buttonActiveFlag=false;
				    		$(".inquiry-inner").scrollTop(this.scrollTopGlobal);//调用最新消息状态
				  }
			})
	    },
	    methods:{
	    		resetPageList(){
	    			//先清空再push
				 this.activeArr=[];
				 this.activeArrText=[];
	    			//判断症状追问的字符
				let _this=this, _pageListStr = this.pageList;
				let pageListOpLength=_pageListStr.length;
				for (let i = 0; i < pageListOpLength; i++) {
					_pageListStr[i].options.forEach(function(val){
						val.isActive=false;
						//默认把不清楚选项选中
						_pageListStr[i].options[0].isActive=true;
						//把选中项放在list
						if(val.isActive === true ){
		        				 _this.activeArr.push(val.key)
		        				 _this.activeArrText.push(val.answer);
		        			}
		             	if(_this.getByteLen(val.text)>10){
		             		_pageListStr[i].strFlag = true;
		             	}
		            });
		            let size = _pageListStr[i].strFlag == true ? 4 : 8;
		            	_pageListStr[i].optionsVal = _this.array_chunk(_pageListStr[i].options, size);
				}
				this.pageList = _pageListStr;
				this.$store.dispatch('pageListGlobalFn', this.pageList);
				this.$store.dispatch('answerGlobalFn', this.activeArrText);
				this.$store.dispatch('answerKeyGlobalFn', this.activeArr);
	    		},
	    		limitInput(idx,val){
	    			let val1=JSON.stringify(val);
	    			if(val1.length>this.vitalSignList[idx].length){
	    				this.vitalSignList[idx].inputValue=val1.slice(0,this.vitalSignList[idx].length)
	    			}
	    		},
	    		judgRange(idx){
	    			if(this.vitalSignList[idx].inputValue>this.vitalSignList[idx].max){
	    				this.vitalSignList[idx].showTip=true;
	    			}else{
	    				this.vitalSignList[idx].showTip=false;
	    			}
	    		},
	    		//获取字符串长度
	    		 getByteLen(val) {
			    var len = 0;
			    for (var i = 0; i < val.length; i++) {
			        var a = val.charAt(i);
			        if (a.match(/[^\x00-\xff]/ig) != null) {
			            len += 2;
			        }
			        else {
			            len += 1;
			        }
			    }
			    return len;
			},
			array_chunk(arr, size){//按照给定长度分割数组
				var result = [];
				for(var i=0,len=arr.length;i<len;i+=size){
				   result.push(arr.slice(i,i+size));
				}
				return result;
			},
		    //年龄加减
	    		addFn(){
	    			this.value8+=1;
	    		},
	    		reduceFn(){
	    			this.value8-=1;
	    		},
	    		//症状追问的卡片选择对应的选项
	    		activeFun(idx,data){
	    			let _pageList=this.pageList[idx];
                 _pageList.options.forEach(function(val){
                 	val.isActive = false;
                 });
                 data.isActive = !data.isActive;
                 this.pageList.splice(idx,1,_pageList);
                	let activeArrInFn=[],
                		activeArrTextInFn=[];
                	 this.pageList.forEach(function(val){
                	 	 val.options.forEach(function(valSon){
                	 	 	if(valSon.isActive === true ){
		        				 activeArrInFn.push(valSon.key);
		        				 if(valSon.answer && valSon.answer!=''){
		        				 	activeArrTextInFn.push(valSon.answer);
		        				 }
		        			}
                	 	 })
                 });
                	this.activeArr=activeArrInFn;
                	this.activeArrText=activeArrTextInFn;
                	this.$store.dispatch('answerGlobalFn', this.activeArrText)
                	this.$store.dispatch('answerKeyGlobalFn', this.activeArr)
            },
            //点击追问症状的确定按钮
            determineInquiriesSym(){
            		if(this.answerGlobal=='' || this.answerKeyGlobal==''){
            			this.$store.dispatch('answerGlobalFn', this.activeArrText);
            			this.talkFetch({ value: this.activeArr},1);
            		}else{
            			this.$store.dispatch('answerGlobalFn', this.answerGlobal);
            			this.talkFetch({ value: this.answerKeyGlobal},1);
            		}
            		console.log(this.answerGlobal,'answerGlobal',this.activeArrText)
            		this.recordUserInp([{ value: this.answerGlobal, type: 'text'}]);
            		this.showMask=false;
            		this.showSymptomsAsk=false;
            },
            //点击其他症状的确定按钮
            sureOtherSymptoms(){
            		this.showButtonAskOtherSym=true;
            		this.talkFetch({ value: this.otherSymptomsArr},1);
            		if(this.otherSymptomsArr.length<=0){
            			this.recordUserInp([{ value:'都没有', type: 'text'}]);
            		}else{
            			this.recordUserInp([{ value: this.otherSymptomsText, type: 'text'}]);
            		}
            		this.otherSymptomsArr=[];
            		this.otherSymptomsText=[];
            		this.actionClickFinish();
            		this.showButtonAskOtherSym=false;
            },
		    suresHideEssentialInfo(){
		    		let vital=this.vitalSignList;
		        this.talkFetch({
		        		value:this.choosePersonKey,gender:this.currentSexy,
		        		age:this.value8,height:!vital[0].inputValue?0:vital[0].inputValue,
		        		weight:!vital[1].inputValue?0:vital[1].inputValue,
		        		temperature:!vital[2].inputValue?0:vital[2].inputValue,
		        		dbp:!vital[3].inputValue?0:vital[3].inputValue,
		        		sbp:!vital[4].inputValue?0:vital[4].inputValue,
		        		heartRate:!vital[5].inputValue?0:vital[5].inputValue,
		        		breath:!vital[6].inputValue?0:vital[6].inputValue,
		        		name:this.choosePersonName ||''
		        },1);
		        this.showMask=false;
		    		this.showEssentialInfo=false;
		    		this.choosePersonnel=false;
		    		let currentGender=this.currentSexy=='male'?'男':'女',
		    			valueText=currentGender+' | '+this.value8+'岁';
		    		if(vital[0].inputValue){
		    			valueText+=' | 身高'+vital[0].inputValue+'cm'
		    		}
		    		if(vital[1].inputValue){
		    			valueText+=' | 体重'+vital[1].inputValue+'kg'
		    		}
		    		if(vital[2].inputValue){
		    			valueText+=' | 体温'+vital[2].inputValue+'℃'
		    		}
		    		if(vital[3].inputValue){
		    			valueText+=' | 高压'+vital[3].inputValue+'mmHg'
		    		}
		    		if(vital[4].inputValue){
		    			valueText+=' | 低压'+vital[4].inputValue+'mmHg'
		    		}
		    		if(vital[5].inputValue){
		    			valueText+=' | 心率'+vital[5].inputValue+'次/分'
		    		}
		    		if(vital[6].inputValue){
		    			valueText+=' | 呼吸频率'+vital[6].inputValue+'次/分'
		    		}
		    	 	this.recordUserInp([{ value: valueText, type: 'text', }]);
		    },
		    //点击新建到选择用户
		    choosePersonneFn(sexy,age,key,name){
		    		this.choosePersonKey=key;
		    		this.choosePersonName=name;
		    		this.showMask=true;
		    		this.showEssentialInfo=true;
		    		if(sexy=='female'){
		    			this.changeSexyWomenFn();
		    		}else{
		    			this.changeSexyMenFn();
		    		}
		    		this.value8=age;
		    },
		    //性别选择
		    changeSexyWomenFn(){
		    		this.currentSexy='female';
		    },
		    changeSexyMenFn(){
		    		this.currentSexy='male';
		    },
		    //是否怀孕
		    choosePregnancy(idx,keys,text){
		    		this.pregnancyFlag = idx;
		    		this.pregnancyKey=keys;
		    		this.pregnancyText=text;
		    },
		    //点击怀孕的确定
		    surePregnancyStatus(){
		    		this.showButtonAskPregnancy=true;
		    		this.talkFetch({ value: this.pregnancyKey},1);
		    		this.recordUserInp([{ value: this.pregnancyText, type: 'text', }]);
            		this.actionClickFinish();
		    },
		    //生命体征选择身高等状态
		    showSignActive(idx){
		    		let checked =this.vitalSignList[idx].checked;
		    		this.vitalSignList[idx].checked = checked === false ? true : true;
		    },
		    hideSignActive(idx){
		    		let checked = this.vitalSignList[idx].checked;
		    		this.vitalSignList[idx].inputValue='';
		    		this.vitalSignList[idx].checked = checked === true ? false : false;
		    },
		    //您是否还有其他症状的选择
		    chooseOtherSymptomsItem(idx){
		    		let _otherSymptomsList = this.otherSymptomsListGlobal,
		    			_this=this,
		    			_otherSymptomsArr=[],
		    			_otherSymptomsText=[];
		    			//先清空再push
		    		this.otherSymptomsArr=[];
		    		this.otherSymptomsText=[];
		        _otherSymptomsList[idx].show = !_otherSymptomsList[idx].show;
		        this.$store.dispatch('otherSymptomsListGlobalFn', _otherSymptomsList);
		        this.otherSymptomsListGlobal.forEach(function(val,index){
		        		if(val.show === true ){
	        				 _otherSymptomsArr.push(val.key);
	        				 _otherSymptomsText.push(val.text)
		        		}
                 });
                this.otherSymptomsArr=_otherSymptomsArr;
                this.otherSymptomsText=_otherSymptomsText;
		    },
		    //保存问诊弹框
		    onConfirm (msg) {
		      if (msg && this.getByteLen(msg)<16) {
		        this.talkFetch({value: 'saveOption',save: true,name:msg},1)
		        this.$store.dispatch('inquiryDataListFn',this.dataList);
		      }
		    },
		    //数组去重
        removeByValue(arr, idVal) {
          for(var i=0; i<arr.length; i++) {
            if(arr[i]['text'] == idVal) {
              arr.splice(i, 1);
              break;
            }
          }
			},
			draw(){
	            	let scrollViewInFn,
	            		num;
		        scrollViewInFn = 'dialog' +this.scrollViewNumGlobal;
		        num = this.scrollViewNumGlobal;
		        this.$store.dispatch('scrollViewNumFn', num)
		        //$refs获取DOM元素以及scrollIntoView相关代码
		        this.$nextTick(() => {
		        		num = this.$refs.box.length-1;
                    this.$refs.box[num].scrollIntoView();
              	})
			},
			//进入当前页面判断 如果params.id==1则是从症状页面返回的，params.id==2是从result进入
			enterPage(){
				 if(this.fromUserPageFlag){
				 	this.draw();
	           		this.dataList=JSON.parse(JSON.stringify(this.inquiryDataList));
					this.clickCommand('agree')
					this.$store.dispatch('fromUserPageFlagFn',false)
				}else if(this.fromRecordsPageFlag){
			   		this.newStart=false;
			   		this.draw();
	           		this.dataList=JSON.parse(JSON.stringify(this.inquiryDataList));
		   }else if(this.continueFlag && this.finishInqFlagGlobal){
		   			//判断是从result页面返回且点击了结束问诊
		          	this.draw();
	           		this.dataList=JSON.parse(JSON.stringify(this.inquiryDataList));
	           		this.pageList=this.pageListGlobal;
	           		this.$store.dispatch('finishInqFlagGlobalFn',false)
	           		this.$store.dispatch('continueFlagFn',false)
	           		this.clickCommand('end-doctor-inquiry')
		   		}else if(this.continueFlag){//是从result页面返回主页面
					this.newStart=true;
		          	this.draw();
	           		this.dataList=JSON.parse(JSON.stringify(this.inquiryDataList));
	           		this.pageList=this.pageListGlobal;
	           		this.$store.dispatch('continueFlagFn',false)
	           		this.$store.dispatch('finishInqFlagGlobalFn',false);
	         	}else if (this.selectedSymptom.length > 0 && !this.fromRecordsPageFlag && !this.finishInqFlagGlobal) {
		            this.dataList=JSON.parse(JSON.stringify(this.inquiryDataList));
		            this.talkFetch({ value: this.selectedSymptom, type: 'symptomList' },1);
	            }else{
		   			//第一次进来页面，执行urlStart
					let sendData={
						id:'',
		    				request: {}
					}
					urlStart(sendData).then(response => {
			            this.successFn(response.data)
					}).catch(error => {
		           	    console.log('error')
		          	});
		   		}
			},
			actionClickFinish(commandid) {
		        if (commandid == 'show-doctor-inquiry-history') {
		            return;
		        }
		        this.disabledAction();
		    },
			disabledAction() {
		        let _dataList = JSON.parse(JSON.stringify(this.dataList)),
		            _len = _dataList.length,
		            _curLi = _dataList[_len - 1],
		            _curStemsArr = _curLi.stems;
		        for (let i = 0; i < _curStemsArr.length; i++) {
		            if ( !_curStemsArr[i].finish) {
		                _curStemsArr[i].finish = true;
		            }
		        }
				this.dataList=_dataList;
				this.draw(this.dataList);
		    },
		    successFn(data){
		    		let  _dataList = JSON.parse(JSON.stringify(this.dataList)),
           		 	 {_list,_options,age, gender,_diseaseResult} = handleDialogueSucCb(data),
           		 	 self=this;
           		 _dataList.push(_list);
      			this.dataOptions=_options;
      			this.gender=gender;
      			this.age=age;
      			this.draw(_dataList);
      			//判断是否显示我同意
      			if(data.talk && data.talk.actions[0].command.id=='show-user-agreement'){
      				this.showUserProtocol=true;
      			}
      			//如果存在inputActions则会出现修改命令
      			if(data.inputActions){
      				this.stepNum+=1;
      				data.inputActions.step=this.stepNum;
      				if(_dataList[_dataList.length-2]){
      					_dataList[_dataList.length-2].answer.push(data.inputActions);
      					this.stepList.push({
		      				step:this.stepNum,
		      				sn:_dataList[_dataList.length-2].sn
		      			});
      				}
      				//只能查看最近的结果
      				for(let i=0; i < _dataList.length-2; i++){
		      			if(_dataList[i]){
		      				if(_dataList[i].answer[1]){
		      					let exsitCheck = false,
		      						exsitIdx = false;
		      					_dataList[i].answer[1].map(function(aVal,aIdx){
		      						if(aVal.command.id == "show-doctor-inquiry-diagnosis"){
		      							exsitCheck = true;
		      							exsitIdx = aIdx;
		      						}
		      					});
		      					if(exsitCheck === true && (exsitIdx !==false)){
		      						_dataList[i].answer[1].splice(exsitIdx, 1);
		      						break;
		      					}
		      				}
		      			}
	      			}
      			}
      			//组装dataList中可修改的元素step
      			if(this.stepList){
      				this.stepList.map(function(lVal, lIdx){
	    					let _sn = lVal.sn;
	    					_dataList.map(function(item, idx){
	    						if(item.sn == _sn){
	    							_dataList[idx].answer[0].step=lVal.step;
	    						}

	    					});
      				});
      			}
      			//置灰之前出现的结果
      			_dataList.map(function(disItem,disIdx){
      				if(disItem.optType=="SaveOptions"){
	      				self.disabledFlag=true;
	      			}else{
	      				self.disabledFlag=false;
	      			}
      			});
      			this.dataList=_dataList;
      			this.dataList.map(function (val, idx) {
      				self.newStart=false;
      				if(val.optType=='DoctorInquiryAskSymptomAttrOptions'){
      					self.pageList=val.asking.options;
      					self.resetPageList(val.asking.title);
      				}else if(val.optType=="SaveOptions"){
      					self.newStart=true;
      				}else{
      					self.newStart=false;
      				}

      				val.stems.map(function(valSon,idxSon){
      					self.inputInquiry=false;
      					if(_diseaseResult){
  							self.$store.dispatch('diagnosisFn',_diseaseResult.diagnoses)
  						}
      					if(valSon.type=='Diagnosis'){
      						//需要把pregnancyFlag:-1,强制置为-1，以防全局变量污染；
      						self.pregnancyFlag=-1;
      					}else if(valSon.type=='ButtonAskOtherSymptom'){
							self.$store.dispatch('otherSymptomsTextGlobalFn',valSon.stem);
							val.asking.options.map(function(oVal, oIdx){
								val.asking.options[oIdx].show = false;
							});
							self.$store.dispatch('otherSymptomsListGlobalFn',val.asking.options);
      					}else if(valSon.type=='ButtonAskSymptom' || valSon.type=='Notification'){
      						self.inputInquiry=true;
      					}
      				})
      			})

		    },
		    // 设置请求的@type
		    setFetchType(type) {
		        let resType = '',
		            optType = '';

		        for (let i = 0; i < fetchType.length; i++) {
		            if (type == fetchType[i].type) {
		                resType = fetchType[i].res || fetchType[i].req;
		                break;
		            }
		        }
		        return { resType };
		    },
		    // 记录用户输入
		    recordUserInp(params) {
		        let _dataList = JSON.parse(JSON.stringify(this.dataList)),
		            _len = _dataList.length,
		            _curLi = _dataList[_len - 1];

		        _curLi.answer = params;
		        this.dataList= _dataList;
		        this.draw(this.dataList);
		   },
		     // talk 流
		    talkFetch(params,snNum) {
		        let  _dataList = JSON.parse(JSON.stringify(this.dataList)),
		            _len = _dataList.length,
		            curLi = _dataList[_len - 1],
		            curId = curLi.id,
		            curSN = curLi.sn,
		            optionType = curLi.optType;
		        let { resType } = this.setFetchType(optionType),
		            input = {
		                "@type": resType
		            },
		            sendData='';
		            sendData = {
			            id: curId,
			            sn: parseFloat(curSN+snNum)
			        };
			     this.$store.dispatch('snGlobalFn',sendData.sn)
		        if (params.value) {
		            if (optionType == 'FreeText') {
		                input.text = params.value;
		            } else if (optionType == 'TextOptions') {
		                input.key = params.value;
		            } else if (optionType == 'AskSymptoms') {
		                if (params.type == 'symptomList') {
		                    input.symptoms = params.value;
		                } else if (params.type == 'symptomText') {
		                    input.text = params.value;
		                }

		            } else if (optionType == 'AskLabItemOptions') {
		                if (params.type == 'skip') {
		                    input.skip = params.value
		                } else if (params.type == 'keys') {
		                    input.keys = params.value;
		                }
		            } else if (optionType == 'SaveOptions') {
		                input.save = params.save;
		                if (params.save) {
		                    input.name = params.name;
		                }
		            } else if (optionType == 'ImageOptions') {
		                input.key = params.value
		            }else if(optionType == 'BasicInfoOptions'){
		            		input.key=params.value;
		            		input.gender=params.gender;
		            		input.age=params.age;
		            		input.height=params.height;
		            		input.weight=params.weight;
		            		input.temperature=params.temperature;
		            		input.dbp=params.dbp;
		            		input.sbp=params.sbp;
		            		input.heartRate=params.heartRate;
		            		input.breath=params.breath;
		            		input.name=params.name;
		            }else if(optionType=='DoctorInquiryAskSymptomAttrOptions'){
		            		input.keys=params.value;
		            }else if(optionType=='DoctorInquiryAskOtherSymptomOptions'){
		            		input.keys=params.value;
		            }

		            sendData.input = input;
		        }
		        if (params.commands) {
		            sendData.commands = [{
		                id: params.commands.id,
		                data:params.commands.data
		            }]
		        }
		        urlTalk(sendData).then(response => {
					this.successFn(response.data)
				})
		        .catch(error => {
	           	    console.log('error')
	          	});
		    },
			clickCommand(commandid,text,step,id,actionTag,sn){
				if(!actionTag){
					this.actionClickFinish(commandid);
				}
				this.buttonActiveFlag=false;
				 if (commandid == 'start-doctor-inquiry') {
				 	this.recordUserInp([{ value: text, type: 'text' }])
				 	this.choosePersonnel=true;
				 	this.talkFetch({
		              commands: {
		                id: commandid
		              }
		           },1)
				 	this.$store.dispatch('selectedSymptomFn','')
            			this.$store.dispatch('inquiryDataListFn','')
				 }else if(commandid == 'show-user-agreement'){ //进入用户协议页面
				 	this.$router.push({path: 'userProtocol'});
				 	this.$store.dispatch('inquiryDataListFn',this.dataList);
				 }else if(commandid == 'show-doctor-inquiry-history'){
				 	//跳转至问诊记录页面
				 	 this.$router.push({path: 'records'});
				 	 this.$store.dispatch('inquiryDataListFn',this.dataList);
				 }else if(commandid=='inputAttr'){
				 	this.showMask=true;
					this.showSymptomsAsk=true;
				 }else if(commandid == 'end-doctor-inquiry'){//点击结束
				 	//新的开始
				 	this.newStart=false;
				 	this.talkFetch({
			              commands: {
			                id: commandid
			              }
			         },1);
			         let endDataList=this.dataList;
			         endDataList.map(function(dval,didx){
			         	dval.end_finish=true;
			         })
				 	this.$store.dispatch('inquiryDataListFn',this.dataList);
				 	//把查看详情的flag置为false;
				 	this.disabledFlag=false;
				 }else if(commandid =='rollback-doctor-inquiry'){ //点击修改步数
				 	let sendStep=this.stepNum-step+2;
				 	let _commands={
			                id: commandid,
			                data:{
			                		steps:JSON.stringify(sendStep)
			                }
			              }
				 	this.talkFetch({
			              commands:_commands
			         },1);
			         //修改操作时传入右侧sn，判断dataList中的sn大于传入的sn时，被清除
			         let dataListLength = this.dataList.length-1;
			         for(var i=dataListLength; i>=0; i--){
			         	if(this.dataList[i].sn >= sn-1){
			         		this.dataList.splice(i,1);
			         	}
			         }
				 }else if(commandid =='show-doctor-inquiry-diagnosis'){//点击查看
				 	 this.toresultPage(id)
				 }else if(commandid=='agree'){
				 	this.recordUserInp([{ value: '我同意', type: 'text' }])
				 	this.showUserProtocol=false;
				 	this.talkFetch({ value:'ok', type: 'TextOptions' },1)
				}else if(commandid=='Notification'){
					this.recordUserInp([{ value: text, type: 'text' }])
				 	this.talkFetch({ value:step, type: 'TextOptions' },1)
				}
			},
			clickToSymptom(){
				let scrollTopNum=$(".inquiry-inner").scrollTop();
				this.$store.dispatch('scrollTopGlobalFn',scrollTopNum);
			    //跳转到症状列表
	             this.$router.push({name: 'symptoms',params:{'gender':this.gender,'age':this.age}});
	             this.dataList.map(function(val,idx){
	             	val.stems.map(function(valSon,idnSon){
	             		if(valSon.type=="ButtonAskSymptom"){
	             			valSon.type='';
	             		}
	             	})
	             })
	             this.$store.dispatch('inquiryDataListFn',this.dataList);

		   },
			showSendFreeImg(){
				this.sendFreeImg=true;
			},
//			//确定自由输入症状
			sendFreeText(){
				if(!this.freeText || !this.freeText==''){
					this.recordUserInp([{ value: this.freeText, type: 'text' }])
        				this.talkFetch({ value: this.freeText, type: 'symptomText' },1)
        				this.inputInquiry=false;
				}
			},
			showPopButtonFn(idx) {
				this.buttonActive=idx;
				this.buttonActiveFlag=true;
			},
			//保存问诊
			saveRecordFn(name){
				if(name && name!=''){
					this.showConfirm=true;
				}else{
					this.showConfirm=false;
					this.talkFetch({value: 'saveOption',save: true},1)
				}
				this.showSuccessToast=true;
			},
			toresultPage(id){
				let scrollTopNum=$(".inquiry-inner").scrollTop();
				this.$store.dispatch('scrollTopGlobalFn',scrollTopNum);
				console.log(this.scrollTopGlobal,'scrollTopGlobalFn')
				let sendId='';
				//点击结果卡片进入结果页面
				if(id && id!=0){
					sendId=id;
				}else{
					sendId=this.dataList[this.dataList.length-1].id;
				}
	    			this.$router.push({name:'result',params:{id:sendId,path:2}});
	    			this.$store.dispatch('inquiryDataListFn',this.dataList);
	    			this.$store.dispatch('pageListGlobalFn', this.pageList);

			},
			otherNoneSymFn(){
				let _this=this;
				this.otherSymptomsListGlobal.map(function(val,index){
					if(val.show ==true){
						console.log(val.show,'val.show',index)
						_this.otherSymptomsListGlobal[index].show=false;
						console.log(_this.otherSymptomsListGlobal[index].show, 2222222222)
					}
		      	});
				console.log(111,this.otherSymptomsListGlobal)
			},
	    },
	}
</script>

<style>
@import url("../assets/css/inquiry.css");
</style>
